﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{

    public sealed class PlayerAudioDelay : IPlayerAudio
    {
        private AudioItem audioItem;
        private AudioSourcePool audiopool;
        private AudioSource audioSource;
        private AudioSourceCtrl audioSourceCtl;
        private Transform root;

        public PlayerAudioDelay(AudioSourcePool pool,AudioItem audioItem,AudioSubItemData audioSubItem,bool loop)
        {
            this.audiopool = pool;
            this.audioItem = audioItem;
            audioSource = pool.Pop(this.audioItem.name);
            this.audioItem.InitAudioSource(audioSource, audioSubItem);
            audioSource.loop = loop;
            float delay = this.audioItem.Delay + audioSubItem.GetDelay();
            float fadein = audioSubItem.GetFadeInTime();
            float fadeout = audioSubItem.GetFadeOutTime();
            this.audioSourceCtl = new AudioSourceCtrl(audioSource, delay, fadein, fadeout);
        }

        public override string ToString()
        {
            return this.audioItem.name;
        }

        public bool IsPlaying { get { return audioSourceCtl.IsPlaying(); } }

        /// <summary>
        /// 剩余时间
        /// </summary>
        /// <returns></returns>
        public float GetRamingTime()
        {
            return this.audioSourceCtl.GetClipLength() - this.audioSourceCtl.GetPlayingTime();
        }

        public void Set(Vector3 pos)
        {
            this.audioSource.transform.position = pos;
        }

        public void Set(Transform root)
        {
            this.root = root;
        }

        public void Play()
        {
            this.audioSourceCtl.Play();
        }

        public void Update()
        {
            if(this.root != null)
            {
                this.audioSource.transform.SetPositionAndRotation(this.root.position, this.root.rotation);
                this.audioSource.transform.localScale = this.root.localScale;
            }
            this.audioSourceCtl.UpdateVolume();
        }

        public void Remove()
        {
            if (this.audioItem != null) this.audioItem.Remove(this);
            if (this.audiopool != null) this.audiopool.Push(this.audioSource);
        }

        public IEnumerator WaitFinish()
        {
            return new WaitUntil(()=> !this.IsPlaying);
        }

        public void Stop()
        {
            this.audioSourceCtl.Stop();
        }


    }
}

